#include <Arduino.h>
#include <OneWire.h>
#include <DS2431.h>
void readDS2431();
void writeDS2431();

#define ONE_WIRE_BUS1 A5 // DS2431连接到数字引脚2
#define ONE_WIRE_BUS2 3 // DS2431连接到数字引脚3
#define LED_PIN 13
OneWire oneWire1(ONE_WIRE_BUS1);
OneWire oneWire2(ONE_WIRE_BUS2);
DS2431 ds2431_1(oneWire1);
DS2431 ds2431_2(oneWire2);

const uint16_t dataSize = 64; // DS2431的存储大小为128字节
uint8_t data[dataSize];

void setup() {
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  delay(1000);
  digitalWrite(LED_PIN, LOW);
  if(!oneWire1.reset()) {
    Serial.println("No DS2431 found on the 1-Wire bus.");
  } else {
    Serial.println("DS2431 found on the 1-Wire bus.");
  }
}

void loop() {
  if (Serial.available()) {
    char command = Serial.read();
    if (command == 'r') {
      Serial.println("Reading DS2431...");
      readDS2431();
    } else if (command == 'w') {
      Serial.println("Writing DS2431...");
      writeDS2431();
    } else if (command == 't') {
      for (uint16_t i = 0; i < dataSize; i++){
        data[i] = i;
      }
      Serial.println("Writing test data...");
    } else {
      Serial.println("Invalid command!");
    }
  }
}

void readDS2431() {
  digitalWrite(LED_PIN, LOW);
  delay(500);
  ds2431_1.read(0, data, dataSize);
  if (true) {
    Serial.println("Read successful:");
    for (uint16_t i = 0; i < dataSize; i++) {
      Serial.print(data[i], HEX);
      Serial.print(" ");
      if((i + 1) % 8 == 0) {
        Serial.println();
      }
    }
    digitalWrite(LED_PIN, HIGH);
} else {
    Serial.println("Read failed!");
  }
}

void writeDS2431() {
  for(uint16_t i = 0; i < dataSize; i += 8) {
    digitalWrite(LED_PIN, LOW);
    if (ds2431_1.write(i, &data[i], 8, true)) {
      oneWire1.reset();
    } else {
      Serial.println("Write failed!");
      digitalWrite(LED_PIN, LOW);
      return;
    }
    digitalWrite(LED_PIN, HIGH);
  }
  Serial.println("Write successful!");
  Serial.println("ROM Data Verify!");
}

/*
E7 10 0 0 0 0 29 EB 
E7 10 0 0 0 0 29 EB 
1 10 60 47 2 0 53 7 
E7 A 3 3 E 18 0 C 
0 0 0 0 0 0 0 1E 
9E 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0
*/